import * as Cesium from '@cesiumjs';

const $defaultOpts = {
  size: 0.02, //最好小于0.02
  speed: 60.0,
}

class RainEffect {

  constructor(viewer, options) {
    if (!viewer) {
      console.error('no viewer object!')
      throw new Error('no viewer object!')
    };
    this._viewer = viewer;
    this.stage = undefined;
    this.options = { ...$defaultOpts, ...options}

    this.defineProperties();
    this.init();
  }

  defineProperties() {
    const _this = this;
    const {options:opt} = this;
    Object.defineProperty(this, "size", {
      get(){return opt.size;},
      set(val){ opt.size = val }
    })
    Object.defineProperty(this, "speed", {
      get(){return opt.speed;},
      set(val){ opt.speed = val }
    })
    Object.defineProperty(this, "show", {
      get(){return _this.stage&&_this.stage.enabled;},
      set(val){ _this.stage&&(_this.stage.enabled = val) }
    })
    Object.defineProperty(this, "viewer", {
      get(){return _this._viewer;}
    })
  }

  init() {
    this.destroy();

    this.stage = new Cesium.PostProcessStage({
      name: 'czm_rain',
      fragmentShader: this.rain(),
      uniforms: {
        size: () => {
          return this.size;
        },
        speed: () => {
          return this.speed;
        }
      }
    });

    this.viewer.scene.postProcessStages.add(this.stage);
  }

  destroy() {
    const {viewer,stage} = this;
    stage && viewer.scene.postProcessStages.remove(stage);
    // stage && stage.destroy();
    this.stage = null;
  }

  //雨着色器
  rain() {
    return 'uniform sampler2D colorTexture;\n' +
      'varying vec2 v_textureCoordinates;\n' +
      '	float hash(float x){\n' +
      '	     return fract(sin(x*133.3)*13.13);\n' +
      '	 }\n' +
      '	void main(void){\n' +
      '	     float time = czm_frameNumber / 600.0;\n' +
      '	     vec2 resolution = czm_viewport.zw; \n' +
      '	     vec2 uv=(gl_FragCoord.xy*2.-resolution.xy)/min(resolution.x,resolution.y);\n' +
      '	     vec3 c=vec3(.6,.7,.8); \n' +
      '	     float a=-.4;\n' +
      '	     float si=sin(a),co=cos(a);\n' +
      '	     uv*=mat2(co,-si,si,co);\n' +
      '	     uv*=length(uv+vec2(0,4.9))*.3+1.;\n' +
      '	     float v=1.-sin(hash(floor(uv.x*100.))*2.);\n' +
      '	     float b=clamp(abs(sin(20.*time*v+uv.y*(5./(2.+v))))-.95,0.,1.)*20.;\n' +
      '	     c*=v*b; \n' +
      '	     gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), vec4(c,1), 0.5); \n' +
      '	}';
  }
}

export default RainEffect;
